package com.example.waternetwork.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.waternetwork.api.model.R;
import com.example.waternetwork.api.system.entity.User;
import com.example.waternetwork.api.system.service.IUserService;
import com.example.waternetwork.api.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 认证控制器
 * </p>
 *
 * @author auto gen
 * @since 2025-06-30
 */
@RestController
@RequestMapping("/system/auth")
@Tag(name = "认证管理", description = "提供用户登录等基础认证功能")
public class AuthController {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private IUserService userService;


    @PostMapping("/login")
    @Operation(
        summary = "用户登录",
        description = "通过提供的用户名和密码进行身份验证，并返回 JWT Token。",
        responses = {
            @ApiResponse(responseCode = "200", description = "登录成功，返回 Bearer Token", content = @Content(schema = @Schema(implementation = R.class))),
            @ApiResponse(responseCode = "400", description = "用户名或密码为空"),
            @ApiResponse(responseCode = "401", description = "用户不存在或密码错误")
        }
    )
    public R login(
        @Parameter(description = "登录用户名", required = true) @RequestParam String username, 
        @Parameter(description = "登录密码", required = true) @RequestParam String password) {

        if (username == null || password == null) {
            return R.fail("用户名或密码不能为空");
        }
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (null  == user) {
            return R.fail("用户不存在");
        }
        if (user.getPassword().equals(password)) {
            String token = jwtUtils.generateToken(username,user.getName(),user.getId());
            return R.ok("Bearer " + token);
        } else {
            return  R.fail("用户名或密码错误");
        }
    }
}
